package com.qiwx.pigeon.activity.manager;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.jzg.lib.crash.LogsActivity;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.LogUtil;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.Utils.SharedPreferencesUtil;
import com.qiwx.pigeon.app.AppContext;
import com.qiwx.pigeon.base.BaseActivity;
import com.qiwx.pigeon.base.Constant;
import com.qiwx.pigeon.widget.ArrowView;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @description
 * @Author qiwx
 * @Date 2020-04-11 14:48
 * 设置页面
 **/
public class SettingActivity extends BaseActivity {
    @BindView(R.id.btn_db_insert)
    Button btnDbInsert;
    @BindView(R.id.btn_db_export)
    Button btnDbExport;
    @BindView(R.id.lin_db)
    LinearLayout linDb;
    @BindView(R.id.edt_period_cd)
    EditText edtPeriodCd;

    @BindView(R.id.edt_period_cz)
    EditText edtPeriodCz;

    @BindView(R.id.edt_period_kw)
    EditText edtPeriodKw;

    @BindView(R.id.edt_period_xz)
    EditText edtPeriodXz;

    @BindView(R.id.txt_db_localpath)
    TextView txtDbLocalpath;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_return)
    ArrowView titleReturn;
    @BindView(R.id.llTitle)
    LinearLayout llTitle;
    @BindView(R.id.rb_day)
    RadioButton rbDay;
    @BindView(R.id.rb_minute)
    RadioButton rbMinute;
    @BindView(R.id.btn_gotime)
    Button btnGotime;

    String sdcard = "";
    File dbFile = null;
    @BindView(R.id.edt_period_cxkw)
    EditText edtPeriodCxkw;
    @BindView(R.id.btn_log)
    Button btnLog;


    @Override
    public int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    public void initAfterOnCreate() {
        initView();
        initPeriod();
        initDb();

    }

    private void initView() {
        titleReturn.changeArrowLeft();
        titleContent.setText("设置");
        if (AppContext.isGoTimeByMinute) {
            rbMinute.setChecked(true);
        } else {
            rbDay.setChecked(true);
        }
    }

    private void initPeriod() {
        int checkEgg = SharedPreferencesUtil.getPeriodValue(this, Constant.TYPE_CD);
        edtPeriodCd.setText(checkEgg + "");
        int checkBaby = SharedPreferencesUtil.getPeriodValue(this, Constant.TYPE_BABY);
        edtPeriodCz.setText(checkBaby + "");
        int kw = SharedPreferencesUtil.getPeriodValue(this, Constant.TYPE_KW);
        edtPeriodKw.setText(kw + "");
        int layegg = SharedPreferencesUtil.getPeriodValue(this, Constant.TYPE_XZ);
        edtPeriodXz.setText(layegg + "");
        int cxkw = SharedPreferencesUtil.getPeriodValue(this, Constant.TYPE_CXKW);
        edtPeriodCxkw.setText(cxkw + "");

    }

    private void initDb() {
        sdcard = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
        if (sdcard != null) {
//
            File dir = new File(sdcard + "pigeon/");
            if (!dir.exists()) {
                dir.mkdir();
            }
            dbFile = new File(sdcard + "pigeon/pigeon_db.db");
            if (!dbFile.exists()) {
                try {
                    dbFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            showDBLoacal();
        }

    }

    public boolean checkPermisson() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        return false;

    }

    public void showDBLoacal() {
        if (dbFile.exists() && dbFile.length() > 0) {
            txtDbLocalpath.setText("本地备份数据库：" + dbFile.getAbsolutePath());
        }
    }

    public void copyFile(File inFile, File outFile) {

        FileChannel input = null;
        FileChannel output = null;

        try {
            input = new FileInputStream(inFile).getChannel();
            output = new FileOutputStream(outFile).getChannel();
            output.transferFrom(input, 0, input.size());
            MyToast.showLong("操作成功");
            showDBLoacal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            saveStream(input);
            saveStream(output);
        }

    }

    private void insertDB() {
        if (checkPermisson()) {
            if (dbFile != null && dbFile.exists()) {
                String path = LitePal.getDatabase().getPath();
                LogUtil.e("DB", path);
                File localFile = new File(path);
                if (dbFile.length() >= localFile.length()) {
                    copyFile(dbFile, new File(path));
                } else {
                    MyToast.showLong("备份数据库记录没有本地多，无法恢复");
                }


            } else {
                MyToast.showLong("本地没有备份数据库");
            }


        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);

        }

    }

    private void exportDB() {
        if (checkPermisson()) {
            if (dbFile == null || !dbFile.exists()) {
                try {
                    dbFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String path = LitePal.getDatabase().getPath();
            LogUtil.e("DB", path);
            File out = new File(path);
            if (out.length() < dbFile.length()) {
                MyToast.showLong("当前数据库记录比备份少，备份失败");
                return;
            }
            copyFile(new File(path), dbFile);


        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1000) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
//                showWaringDialog();
            }
        }
    }


    private void saveStream(FileChannel fileChannel) {
        if (fileChannel != null) {
            try {
                fileChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void changePeriod(int type, EditText edt) {
        String number = edt.getText().toString();
        if (number == null || number.length() <= 0) {
            MyToast.showLong("数值不能为空");
            return;
        }
        SharedPreferencesUtil.setPeriod(this, type, Integer.valueOf(number));

    }

    private void chageGoTime() {
        changePeriod(Constant.TYPE_CD, edtPeriodCd);
        changePeriod(Constant.TYPE_BABY, edtPeriodCz);
        changePeriod(Constant.TYPE_KW, edtPeriodKw);
        changePeriod(Constant.TYPE_XZ, edtPeriodXz);
        changePeriod(Constant.TYPE_CXKW, edtPeriodCxkw);
        SharedPreferencesUtil.setIsGoTimeByMinute(this, rbMinute.isChecked());
        AppContext.isGoTimeByMinute = SharedPreferencesUtil.getIsGoTimeByMinute(this);
        SharedPreferencesUtil.initPeriod(this);
        MyToast.showLong("操作成功");
    }


    @OnClick({R.id.title_return, R.id.btn_log,R.id.btn_gotime, R.id.btn_db_insert, R.id.btn_db_export})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_return:
                finish();
                break;
            case R.id.btn_gotime:
                chageGoTime();
                break;
            case R.id.btn_db_insert:
                insertDB();
                break;
            case R.id.btn_db_export:
                exportDB();
                break;
            case R.id.btn_log:
                startActivity(new Intent(this, LogsActivity.class));
                break;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
